package blue.blog.core.service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import blue.blog.core.dao.CmsChannelDao;
import blue.blog.core.dao.CmsDocContentDao;
import blue.blog.core.dao.CmsDocDao;
import blue.blog.core.dao.CmsDocFileDao;
import blue.blog.core.model.CmsDoc;
import blue.blog.core.model.CmsDocFile;

@Service
@Transactional
public class CmsDocService
{
	@Resource
	private CmsDocDao cmsDocDao;
	@Resource
	private CmsDocContentDao cmsDocContentDao;
	@Resource
	private CmsDocFileDao cmsDocFileDao;
	@Resource
	private CmsChannelDao cmsChannelDao;
	
	public CmsDocService()
	{
	}
	
	public boolean exist(String url)
	{
		return cmsDocDao.exist(url);
	}
	
	public void add(CmsDoc doc)
	{
		if (cmsDocDao.exist(doc.getUrl()))
			return;
		
		cmsDocDao.save(doc);
		cmsDocContentDao.add(doc.getId(), doc.getSummary(), doc.getContent());
		List<CmsDocFile> fileList = doc.getFileList();
		if (fileList != null && !fileList.isEmpty())
		{
			for (CmsDocFile file : fileList)
			{
				file.setDocId(doc.getId());
			}
			cmsDocFileDao.saveList(fileList);
		}
		cmsChannelDao.incDocs(doc.getChannelId(), 1);
	}

	public void state(List<Integer> idList, Integer state)
	{
		cmsDocDao.state(idList, state);
	}
	
	public void state(Integer id, Integer state)
	{
		cmsDocDao.updateObject(id, "state", state);
	}
	
	public List<CmsDoc> listDetail(CmsDoc doc, int size)
	{
		List<CmsDoc> list = cmsDocDao.list(doc, 0, size);
		if (list == null || list.isEmpty())
			return list;
		
		List<Integer> idList = list.stream().map(CmsDoc::getId).collect(Collectors.toList());
		List<CmsDocFile> fileList = cmsDocFileDao.listByDoc(idList);
		Map<Integer, List<CmsDocFile>> fileMap = fileList.stream().collect(Collectors.groupingBy(CmsDocFile::getDocId));
		for (CmsDoc d : list)
		{
			d.setFileList(fileMap.get(d.getId()));
		}
		return list;
	}
	
}
